package TankFrst;
/*
把消息封装成一个类，便于程序的传输
 */
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TankNewMsg implements Msg{
    int msgType=Msg.TAKE_NEW_MSG;
    Tank tank;
    TankClient tc;

    public TankNewMsg(TankClient tc) {
        this.tc = tc;
    }


    public TankNewMsg(Tank tank) {
        this.tank = tank;
    }

    public void send(DatagramSocket ds, String IP, int udpPort) {
        //利用send方法来发送信息
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//转换为字节输出
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            /*
            将数据打包
            id,tank的横坐标和纵坐标，方向，坦克的好坏
             */
            dos.writeInt(msgType);
            dos.writeInt(tank.id);
            dos.writeInt(tank.x);
            dos.writeInt(tank.y);
            dos.writeInt(tank.dir.ordinal());//在枚举类型的下标值，即方向
            dos.writeBoolean(tank.isGood());
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buf = baos.toByteArray();//转换为字节数组
        DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(IP, udpPort));//将字节数组转换为Data包发送
        try {
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void parse(DataInputStream dis) {
        try {
            int id=dis.readInt();
            //判断这个坦克是否存在，如果存在，就不建立
            if (tc.myTank.id==id){
                return;
            }
            int x=dis.readInt();
            int y=dis.readInt();
            Dir dir=Dir.values()[dis.readInt()];//将方向的下标转换并且存储
            boolean good=dis.readBoolean();
            //tank不存在的时候，新建一个tank
            //查找坦克是否存在，如果不存在就新建一个tank
            boolean exist = false;
            for (int i = 0; i < tc.tanks.size(); i++) {
                Tank t=tc.tanks.get(i);
                if (t.id==id){
                    exist=true;
                    break;
                }
            }
            if (!exist) {
                //向敌人发送自己的tank
                TankNewMsg tnmsg=new TankNewMsg(tc.myTank);
                tc.nc.send(tnmsg);
                Tank t = new Tank(x, y, good, dir, tc);
                t.id = id;
                tc.tanks.add(t);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
